package com.wtwd.device.utils;

import com.wtwd.device.model.vo.TreeVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class TreeUtil {
    /**
     * * 生成树
     * * 1.转换树节点对象并且将数据以pid为key,该父类子节点集合为值 放入Map
     * * 2.遍历Map中每个节点数据,设置节点的子节点,并找出被使用的子节点
     * * 3.找出Map中未使用过的子节点则这些节点为顶级节点
     *
     * @param treeData
     * @return
     */
    public static List<? extends TreeVO> createTree(List<? extends TreeVO> treeData) {
        if (treeData == null || treeData.size() == 0) {
            return null;
        }
        Map<Integer, List<TreeVO>> childMap = treeData.stream().collect(Collectors.groupingBy(data -> data.getPid()));
        List<Integer> usePid = new ArrayList<>(treeData.size());
        childMap.forEach((key, value) -> {
            value.forEach(data -> {
                data.setChildren(childMap.get(data.getId()));
                usePid.add(data.getId());
            });
        });
        List<Integer> noUsePids = new ArrayList<>(childMap.size());
        for (Integer pid : childMap.keySet()) {
            if (!usePid.contains(pid)) {
                noUsePids.add(pid);
            }
        }
        List<TreeVO> treeList = childMap.get(noUsePids.get(0));
        for (int i = 1; i < noUsePids.size(); i++) {
            treeList.addAll(childMap.get(noUsePids.get(i)));
        }
        return treeList;
    }

}
